package com.qingcheng.mq;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @Author:boy
 * @Date:2019/7/25
 * @description:
 * @ModifiedBy:
 */
@Component
public class GoodsDelIndexConsumer implements MessageListener {
    //日记
    private Logger logger = LoggerFactory.getLogger(GoodsDelIndexConsumer.class);
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Reference
    private SkuService skuService;
    public void onMessage(Message message) {
        try {
            String id = new String(message.getBody(), "utf-8");
            this.delIndex(id);
        } catch (UnsupportedEncodingException e) {
            logger.error("消息编码异常", e);
        }

    }

    /**
     * 根据spuId删除索引库信息
     *
     * @param id spuId
     */
    private void delIndex(String id) {
        //根据spuID查询skuId
        List<String> skuIds = skuService.findIdsBySpuId(id);
        if (skuIds != null && skuIds.size() > 0) {
            //创建批处理对象
            BulkRequest bulkRequest = new BulkRequest();
            for (String skuId : skuIds) {
                //创建删除查询请求
                DeleteRequest deleteRequest = new DeleteRequest("sku").type("doc");
                //封装条件
                deleteRequest.id(skuId);
                bulkRequest.add(deleteRequest);
            }
            try {
                //批量删除
                restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                logger.error("索引库批量删除异常", e);
            }
        }


    }
}
